package net.atomarrow.render;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.atomarrow.ioc.ActionContext;

public class JspRender extends Render{
    public static final String REDIRECT_PATH="REDIRECT_PATH";
    public static final String REDIRECT_TYPE="REDIRECT_TYPE";
    public static final String REDIRECT_TYPE_REDIRECT="REDIRECT_TYPE_REDIRECT";
    public static final String REDIRECT_TYPE_FORWARD="REDIRECT_TYPE_FORWARD";
    
	@Override
	public void render() {
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request =context.getRequest();
		HttpServletResponse response =context.getResponse();
		try {
		    if(getAttr(REDIRECT_TYPE).equals(REDIRECT_TYPE_FORWARD)){
		        String path= getAttr(REDIRECT_PATH);
		        if(!path.startsWith("/")){
		            path = getCurrentPath(context, request, path);
		        }
		        request.getRequestDispatcher(path).forward(request, response);
		    }else if(getAttr(REDIRECT_TYPE).equals(REDIRECT_TYPE_REDIRECT)){
		    	String path= getAttr(REDIRECT_PATH);
		        if(!path.startsWith("/")){
		            path = getCurrentPath(context, request, path);
		        }
		        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		        path = basePath+path;
		        response.sendRedirect(path);
		    }else{
		        return;
		    }
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getCurrentPath(ActionContext context,
			HttpServletRequest request, String path) {
		String currentPath = request.getServletPath();
		currentPath=currentPath.replace(context.getAction().getMethodName(), "");
		if(currentPath.endsWith("//")){
			currentPath=currentPath.substring(0,currentPath.length()-1);
		}
		if(!currentPath.endsWith("/")){
		    currentPath=currentPath+"/";
		}
		if(ActionContext.getContext().getUrlParam(0)!=null){
		    currentPath=currentPath.substring(0,currentPath.length()-1);
		    currentPath=currentPath.substring(0, currentPath.lastIndexOf("/"));
		}
		if(currentPath.endsWith("//")){
		    currentPath=currentPath.substring(0,currentPath.length()-1);
		}
		path=currentPath+path;
		return path;
	}

}
